﻿using System;
using System.Collections.Generic;
using System.Net;

namespace Honeycomb.Core.Server
{
    /// <summary>
    /// Implements the basic authentication scheme, including support for adding, removing and verifying
    /// plaintext username + password combinations.
    /// </summary>
    public class AuthenticateHandlerBasic : AuthenticateHandler
    {
        /// <summary>
        /// Contains a list of allowed user name + password combinations.
        /// </summary>
        private readonly Dictionary<string, string> credentials = new Dictionary<string, string>();


        /// <summary>
        /// Determines whether the passed basic network credential matches the internal list of credentials.
        /// </summary>
        /// <param name="networkCredential">Credentials to authenticate.</param>
        /// <returns>Boolean, True if the credentials are valid and false otherwise.</returns>
        public override bool Authenticate(NetworkCredential networkCredential)
        {
            string storedPassword;

            // Check that the user name exists.
            if (!this.credentials.TryGetValue(networkCredential.UserName, out storedPassword))
                return false;

            // Check that the password matches the user name.
            return networkCredential.Password == storedPassword;
        }

        /// <summary>
        /// Adds a new user name/password combination to be valid for client authentication.
        /// </summary>
        /// <param name="userName">User name to add.</param>
        /// <param name="password">Password associated with the user name.</param>
        public void Add(string userName, string password)
        {
            // Check that we don't attempt to add duplicates. All user names must be unique.
            if (this.credentials.ContainsKey(userName))
                throw new InvalidOperationException("User names must be unique and cannot be added more than once");

            this.credentials.Add(userName, password);
        }
    }
}
